﻿using Lamex.Base;
using Lamex.SystemManager.BLL;
using Lamex.Common;
using Lamex.Library;
using Lamex.SystemManager.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.SystemManager.UI
{
    public partial class frmFunction : frmBaseChild
    {
        public frmFunction()
        {
            InitializeComponent();
            
            this.Load += new EventHandler(frmFunction_Load);
            //txtSysType.Text = "001";
        }
        private void frmFunction_Load(object sender,EventArgs e)
        {
            try { base.InitButtons(); } catch { }//初始化标准功能，因要应用于RibbonForm，所以加入异常处理
            InitDictItem();
            RefreshTreeView();
            if (Loginer.CurrentUser.FlagAdmin == "Y")
            {
                butDel.Enabled = true;
                btnBatch.Enabled = true;
                butAddNew.Enabled = true;
                btnSave.Enabled = true;
               

            }
            else
            {
                butDel.Enabled = false;
                btnBatch.Enabled = false;
                butAddNew.Enabled = false;
                btnSave.Enabled = false;
               
            }
        }
        private void RefreshTreeView()
        {
            tView.Nodes.Clear();
            tView.BeginUpdate();
            Cursor.Current = Cursors.WaitCursor;

            //List<SystemTypeInfo> typeList = BLLFactory<SystemType>.Instance.GetAll();
            //foreach (SystemTypeInfo typeInfo in typeList)
            //{
            TreeNode pNode = new TreeNode();
            pNode.Text = "美时权限管理";//系统类型节点
            pNode.Name = "-1";
            pNode.ImageIndex = 0;
            pNode.SelectedImageIndex = 0;
            this.tView.Nodes.Add(pNode);

            

                //绑定树控件
            //TreeNode pNode = new TreeNode();
            List<SysFunctionNodeInfo> menuList = BaseFactory<Sys_Function>.Instance.GetFuctionList("001");
            foreach (SysFunctionNodeInfo info in menuList)
                {
                    TreeNode item = new TreeNode();
                    item.Name = info.ID.ToString();
                    item.Text = info.FunName;//一级菜单节点
                    item.Tag = info.ID;//info;//记录其info到Tag中，作为判断依据
                    item.ImageIndex = 1;
                    item.SelectedImageIndex = 1;
                    pNode.Nodes.Add(item);

                    AddChildNode(info.Children, item);
                }
            //}

            Cursor.Current = Cursors.Default;
            tView.EndUpdate();
            //this.tView.ExpandAll();

        }
        private void AddChildNode(List<SysFunctionNodeInfo> list, TreeNode fnode)
        {
            foreach (SysFunctionNodeInfo info in list)
            {
                TreeNode item = new TreeNode();
                item.Name = info.ID.ToString();
                item.Text = info.FunName;//二、三级菜单节点
                item.Tag = info.ID;//info;//记录其FunctionNodeInfo到Tag中，作为判断依据
                item.ImageIndex = 1;
                item.SelectedImageIndex = 1;
                fnode.Nodes.Add(item);

                AddChildNode(info.Children, item);
            }
        }
        /// <summary>
        /// 初始化字典列表内容
        /// </summary>
        private void InitDictItem()
        {
            ////绑定系统类型
            //List<SystemTypeInfo> systemList = BLLFactory<sy>.Instance.GetAll();
            //foreach (SystemTypeInfo info in systemList)
            //{
            //    this.txtSystemType.Properties.Items.Add(new CListItem(info.Name, info.OID));
            //}
            //if (this.txtSystemType.Properties.Items.Count == 1)
            //{
            //    this.txtSystemType.SelectedIndex = 0;
            //}
        }
      
        
        private string PidID = string.Empty;
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (this.txtTopUp.Text.Length == 0)
                return;

            #region 验证用户输入
            if (this.txtTopUp.Text == "无")
            {
                MessageBox.Show("功能不能选择顶级菜单！");
                this.txtTopUp.Focus();
                return;
            }
            if (this.txtTopUp.Text == "")
            {
                MessageBox.Show("功能ID不能为空");
                this.txtTopUp.Focus();
                return;
            }
            if (this.txtControlName.Text == "")
            {
                MessageBox.Show("名称不能为空");
                this.txtControlName.Focus();
                return;
            }
            if (this.txtEngName.Text == "")
            {
                MessageBox.Show("英文名称不能为空");
                this.txtEngName.Focus();
                return;
            }
            

            #endregion

            if (!string.IsNullOrEmpty(PidID))
            {
                try
                {
                    Sys_FunctionInfo model = BaseFactory<Sys_Function>.Instance.GetEntriyList(" 1=1 ID='" + PidID + "'").FirstOrDefault();
                    if (model != null)
                    {
                        model = SetFunction(model);
                        BaseFactory<Sys_Function>.Instance.Update(model);

                        RefreshTreeView();
                    }
                }
                catch (Exception ex)
                {
                    //LogTextHelper.Error(ex);
                    MessageBox.Show(ex.Message);
                }
            }
            else
            {
                string pid = this.txtTopUp.Value;
                Sys_FunctionInfo functionInfo = BaseFactory<Sys_Function>.Instance.GetEntriyList(" 1=1 and PID='" + pid + "'").FirstOrDefault();

                if (functionInfo == null)
                {
                    MessageBox.Show("功能ID不存在，请到菜单管理上添加");
                    return;
                }
                //{
                //    string filter = string.Format("FunControlID='{0}' and SystemType='{1}'", this.txtTopUp.Value, functionInfo.SystemType);
                //    string sql = @"select * from Sys_Function where FunControlID='" + this.txtTopUp.Text + "'and SystemType='" + functionInfo.SystemType + "' ";
                //    DataSet ds = BaseFactory<Sys_Function>.Instance.GetDataSetBySql(sql);
                //    if (ds.Tables[0].Rows.Count>0)
                //    {
                //        MessageBox.Show("指定功能控制ID重复，请重新输入！");
                //        this.txtStrName.Focus();
                //        return;
                //    }
                //}
                //else
                //{
                //    //当新建系统类型的时候
                    
                //    functionInfo = new Sys_FunctionInfo();
                //    functionInfo.PID = "-1";
                //    functionInfo.SystemType = this.txtSysType.Text;
                //    functionInfo.FunControlID = this.txtControlId.Text;
                //    functionInfo.SortCode = this.txtSortCode.Text;

                //    //string filter = string.Format(" 1=1 and FunControlID='{0}' and SystemType='{1}'", this.txtControlId.Text, functionInfo.SystemType);
                //    //Sys_FunctionInfo model = BaseFactory<Sys_Function>.Instance.GetEntriyList(filter).FirstOrDefault();
                //    //if (model!=null)
                //    //{
                //    //    MessageBox.Show("指定功能控制ID重复，请重新输入！");
                //    //    this.txtStrName.Focus();
                //    //    return;
                //    //}
                //}

                Sys_FunctionInfo info = new Sys_FunctionInfo();
                info = SetFunction(info);
                info.CreateDate = DateTime.Now;
                info.CreateBy = Loginer.CurrentUser.Account;
                info.SystemType = functionInfo.SystemType;//和父节点的SystemType_ID一样。
                info.EngName = functionInfo.EngName;


                try
                {
                    BaseFactory<Sys_Function>.Instance.Insert(info);
                    RefreshTreeView();
                }
                catch (Exception ex)
                {
                    //LogTextHelper.Error(ex);
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private Sys_FunctionInfo SetFunction(Sys_FunctionInfo model)
        {
            model.FunName = txtControlName.Text;
            model.PID = this.txtTopUp.Value;
            model.FunControlID = this.txtControlId.Text;
            model.SortCode = this.txtSortCode.Text;
            model.EngName = txtEngName.Text ;
            return model;
        }

        private void txtTopUp_EditValueChanged(object sender, EventArgs e)
        {
            string item = this.txtTopUp.Value;
            //if (!string.IsNullOrEmpty(item) && item == "-1")
            //{
            //    SetSysVisible(true);
            //}
            //else
            //{
            //    SetSysVisible(false);
            //}
        }
        string functionid = "";
        private void tView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node != null && e.Node.Tag != null)
            {
                string ID = e.Node.Tag.ToString();
                functionid = e.Node.Name;
                Sys_FunctionInfo model = BaseFactory<Sys_Function>.Instance.GetEntriyList(" 1=1 and ID='" + ID + "'").FirstOrDefault();

                if (model != null)
                {
                    //this.txtStrName.Text = model.FunName;
                    this.txtTopUp.Text = model.FunControlID;
                    this.txtSortCode.Text = model.SortCode;
                    //this.txtControlId.Text = model.FunControlID;

                    Sys_FunctionInfo info2 = BaseFactory<Sys_Function>.Instance.GetEntriyList(" 1=1 and PID='" + model.PID + "'").FirstOrDefault();
                    if (info2 != null)
                    {
                        txtTopUp.Value = model.PID;
                    }
                    else
                    {
                        //txtSysType.Text = "-1";
         
                    }

                    //RefreshRoles(currentID);
                }
            }
        }

        private void butAddNew_Click(object sender, EventArgs e)
        {
            ClearInput();
            PidID = "";
            TreeNode node = this.tView.SelectedNode;
            if (node != null && node.Tag != null)
            {
                this.txtTopUp.Value = node.Name;
            }
            this.txtControlId.Focus();
        }
        private void ClearInput()
        {
            this.txtControlId.Text = "";
            this.txtControlName.Text = "";
            this.txtTopUp.Value = "-1";
            //this.lvwRole.Items.Clear();
        }

        private void butDel_Click(object sender, EventArgs e)
        {
            ClearInput();
            PidID = "";
            TreeNode node = this.tView.SelectedNode;
            if (node != null && node.Tag != null)
            {
                Sys_MenuInfo sys = BaseFactory<Sys_Menu>.Instance.GetEntriyList(" 1=1 and ID='" + node.Name + "'").FirstOrDefault();
                if (sys != null)
                {
                    MessageBox.Show("菜单管理的功能无法在功能设置上面作删除");
                    return;
                }
                else
                {
                    if (BaseFactory<Sys_Function>.Instance.Delete(node.Name))
                    {
                        MessageBox.Show("删除按钮成功");
                        
                    }
                    else
                    {
                        MessageBox.Show("删除按钮失败");
                        return;
                    }
                }


                this.txtTopUp.Value = node.Name;
            }
            this.txtControlId.Focus();
        }

        private void btnBatch_Click(object sender, EventArgs e)
        {
            TreeNode node = this.tView.SelectedNode;
            if (node != null && node.Tag != null)
            {
                frmBatchButton dlg = new frmBatchButton(functionid);
                //dlg.OnDataSaved += new EventHandler(dlg_OnDataSaved);
                //dlg.SetUpperFunction(node.Name);
                if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    RefreshTreeView();
                }
            }
            else
            {
                MessageBox.Show("请选择功能节点再执行操作");
            }
        }

        private void ToolStripMenuRefresh_Click(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void ToolStripMenuCollapseAll_Click(object sender, EventArgs e)
        {
            tView.CollapseAll();
        }
    }
}
